import { DISCOVER_GET_LIST, DISCOVER_POST_LIKE, DISCOVER_POST_COMMENT } from '../mutation-types';
import { getDiscoverList, discoverLikeApi, discoverCommentApi } from '../../api';

function getInitialState() {
  return {
    list: [],
    currentPage: 1,
    pageCount: 1,
    hasNextPage: null,
    loading: false,
    noData: true,
    likeText: '赞'
  };
}

const state = getInitialState();

const getters = {
  menu: (state) => state.menu,
  list: (state) => state.list,
  loading: (state) => state.loading,
  hasNextPage: (state) => state.hasNextPage,
  noData: (state) => state.noData,
  currentPage: (state) => state.currentPage,
  likeText: (state) => state.likeText
};

const mutations = {
  [DISCOVER_GET_LIST](state, payload) {
    console.log(state);
    console.log(payload);
    state.currentPage = payload.currentPage;
    state.pageCount = payload.pageCount;
    if (payload.items.length !== 0) {
      state.hasNextPage = payload.hasNextPage;
    } else {
      state.hasNextPage = null;
    }
    const oldList = state.list;
    state.list = oldList.concat(payload.items);
    state.noData = payload.noData;
    state.loading = false;
    console.log('now state: -> ', state);
  },
  loading(state) {
    state.loading = true;
  },
  destroyedState(state) {
    state = Object.assign(state, getInitialState());
    console.log('destroyed state: -> ', state);
  },
  [DISCOVER_POST_LIKE](state, payload) {
    const list = state.list;
    // 找到修改的元素
    list.map((curr) => {
      if (curr.id === payload.id) {
        curr.liked = payload.liked;
        // 如果点赞成功 点赞数+ 1  将姓名推入点赞列表 否则反之
        if (payload.liked) {
          curr.like_num += 1;
          curr.likes.push(payload.name);
        } else {
          curr.like_num -= 1;
          let index = curr.likes.indexOf(payload.name);
          if (index > -1) {
            curr.likes.splice(index, 1);
          }
        }
      }
    });
    if (payload.liked) {
      state.likeText = '取消';
    } else {
      state.likeText = '赞';
    }
    state.list = list;
  },
  refreshLikeText(state, payload) {
    console.log(payload);
    if (state.list[payload.index].liked) {
      state.likeText = '取消';
    } else {
      state.likeText = '赞';
    }
  },
  [DISCOVER_POST_COMMENT](state, payload) {
    const list = state.list;
    // 找到修改的元素
    list.map((curr) => {
      if (curr.id === payload.id) {
        curr.comments.push(payload.data);
      }
    });
  }
};

const actions = {
  // 获取分类列表的课程数据
  [DISCOVER_GET_LIST]({ commit }, data) {
    commit({type: 'loading'});
    console.log(data);
    getDiscoverList(data.page, data.code)
      .then(res => {
        console.log(res);
        const currentPage = res.data.meta.currentPage;
        const pageCount = res.data.meta.pageCount;
        const hasNextPage = currentPage < pageCount && currentPage !== 0;
        const items = res.data.items;
        items.map((curr) => {
          curr['publishTime'] = timestampFormat(curr.time);
        });
        commit({
          type: DISCOVER_GET_LIST,
          items: items,
          currentPage: currentPage,
          pageCount: pageCount,
          hasNextPage: hasNextPage,
          noData: res.data.items.length === 0
        });
      });
  },
  // 在请求参数切换时，清空list数据
  destroyedState({ commit }) {
    commit({
      type: 'destroyedState'
    });
  },
  [DISCOVER_POST_LIKE]({ commit, dispatch }, data) {
    discoverLikeApi({
      dynamic_id: data.id
    }).then(res => {
      console.log(res);
      commit({
        type: DISCOVER_POST_LIKE,
        liked: res.data,
        id: data.id,
        name: data.name
      });
    });
  },
  [DISCOVER_POST_COMMENT]({ commit, rootGetters }, data) {
    discoverCommentApi({
      dynamic_id: data.id,
      content: data.content
    }).then(res => {
      console.log(res);
      commit({
        type: DISCOVER_POST_COMMENT,
        data: res.data,
        id: data.id
      });
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};

function timestampFormat(timestamp) {
  function zeroize(num) {
    return (String(num).length === 1 ? '0' : '') + num;
  }

  var curTimestamp = parseInt(new Date().getTime() / 1000);// 当前时间戳
  var timestampDiff = curTimestamp - timestamp;// 参数时间戳与当前时间戳相差秒数

  var curDate = new Date(curTimestamp * 1000);// 当前时间日期对象
  // 参数时间戳转换成的日期对象
  var tmDate = new Date(timestamp * 1000);

  let Y = tmDate.getFullYear();
  let m = tmDate.getMonth() + 1;
  let d = tmDate.getDate();
  let H = tmDate.getHours();
  let i = tmDate.getMinutes();
  // let s = tmDate.getSeconds();

  if (timestampDiff < 60) {
    // 一分钟以内
    return '刚刚';
  } else if (timestampDiff < 3600) {
    // 一小时前之内
    return Math.floor(timestampDiff / 60) + '分钟前';
  } else if (curDate.getFullYear() === Y && curDate.getMonth() + 1 === m && curDate.getDate() === d) {
    return '今天' + zeroize(H) + ':' + zeroize(i);
  } else {
    // 参数中的时间戳加一天转换成的日期对象
    var newDate = new Date((curTimestamp - 86400) * 1000);
    if (newDate.getFullYear() === Y && newDate.getMonth() + 1 === m && newDate.getDate() === d) {
      return '昨天' + zeroize(H) + ':' + zeroize(i);
    } else if (curDate.getFullYear() === Y) {
      return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
    } else {
      return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
    }
  }
}
